import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { getUserTempId } from './auth'
import store from '@/store'

/*
  1.请求拦截器
  2.响应拦截器
  3.进度条
*/

const request = axios.create({
  baseURL: '/api',
})

//请求拦截器
request.interceptors.request.use((config) => {
  NProgress.start() // 进度条开始

  if (/^\/mock/.test(config.url)) {
    config.baseURL = ''
  }
  const token = store.state.user.token
  if (token) {
    config.headers.token = token
  } else {
    config.headers.userTempId = getUserTempId()
  }

  return config
})

//响应拦截器
request.interceptors.response.use(
  function (response) {
    NProgress.done()
    if (response.data.code === 200) {
      return response.data.data
    } else {
      if (response.data.message !== '支付中') alert(response.data.message)
      return Promise.reject(response.data.message)
    }
  },
  function (error) {
    NProgress.done()
    alert(error)
    return Promise.reject(error)
  }
)
export default request
